#!/bin/bash
export JAVA_HOME=/opt/java/jdk-17.0.12
export JRE_HOME=$JAVA_HOME/jre
export CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin

APP_NAME=/opt/sky-server/sky-server-1.0-SNAPSHOT.jar
REDIS_CONF=/opt/redis/myredis/redis7.conf

# 使用说明，用来提示输入参数
usage() {
    echo "Usage: sh log.sh [start|stop|restart|status|redis-start|redis-stop]"
    exit 1
}

# 检查程序是否在运行
is_exist(){
  pid=$(ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}')
  # 如果不存在返回1，存在返回0
  if [ -z "${pid}" ]; then
    return 1
  else
    return 0
  fi
}

# 启动方法
start(){
  is_exist
  if [ $? -eq 0 ]; then
    echo "${APP_NAME} is already running. pid=${pid}"
  else
    nohup java -jar ${APP_NAME} >log.out 2>&1 &
    echo "Started Java application with pid=$!"
  fi
}

# 停止方法
stop(){
  is_exist
  if [ $? -eq "0" ]; then
    kill -9 $pid
    echo "Stopped Java application with pid=${pid}"
  else
    echo "${APP_NAME} is not running"
  fi
}

# 输出运行状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_NAME} is running. Pid is ${pid}"
  else
    echo "${APP_NAME} is NOT running."
  fi
}

# 重启
restart(){
  stop
  sleep 5
  start
}

# 启动 Redis 服务
redis_start() {
  if pgrep -f "redis-server $REDIS_CONF" > /dev/null; then
    echo "Redis server is already running with config $REDIS_CONF"
  else
    nohup redis-server $REDIS_CONF > redis.log 2>&1 &
    echo "Started Redis server with config $REDIS_CONF"
  fi
}

# 停止 Redis 服务
redis_stop() {
  if pgrep -f "redis-server $REDIS_CONF" > /dev/null; then
    pkill -f "redis-server $REDIS_CONF"
    echo "Stopped Redis server with config $REDIS_CONF"
  else
    echo "No Redis server running with config $REDIS_CONF"
  fi
}

# 根据输入参数，选择执行对应方法，不输入则执行使用说明
case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  "redis-start")
    redis_start
    ;;
  "redis-stop")
    redis_stop
    ;;
  *)
    usage
    ;;
esac
